const state = {
  count: 1,
  cart: JSON.parse(localStorage.getItem('cart') || '[]'),
};

const mutations = {
  addCart(state, goodsinfo) {
    var flag = false;
    state.cart.forEach((item) => {
      if (item.id === goodsinfo.id) {
        item.count += goodsinfo.count;
        flag = true;
      }
    });
    if (!flag) {
      state.cart.push(goodsinfo);
    }
    localStorage.setItem('cart', JSON.stringify(state.cart));
  },
  allCheck(state) {
    state.cart.isChecked=!state.cart.isChecked
    state.cart.forEach((item) => {
      item.isChecked=!item.isChecked
    });
  },
  addShop(state, num) {
    state.cart.forEach((item) => {
      if (item.id === num) {
        item.count += 1;
        localStorage.setItem('cart', JSON.stringify(state.cart));
      }
      console.log(num);
    });
  },
  subShop(state, num) {
    state.cart.forEach((item) => {
      if (item.id === num) {
        item.count -= 1;
        localStorage.setItem('cart', JSON.stringify(state.cart));
      }
      console.log(num);
    });
  },
};

const actions = {};

const getters = {
  getAllCount(state) {
    let c = 0;
    state.cart.forEach((item) => {
      c += item.count;
    });
    return c;
  },
  getAllPrice(state) {
    let p = 0;
    state.cart.forEach((item) => {
      if (item.isChecked) {
        p += item.price * item.count;
      }
    });
    return p;
  },
  getAllCheck(state) {
    return state.cart.every((item) => {
      return item.isChecked;
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
